import store from '@/store'

function checkRole(el, binding) {
  const { value } = binding
  const userType = store.getters.userType
  const roles = store.getters.roles

  if (value && value instanceof Array && value.length > 0) {
    const rolePermissions = value

    const hasRole = roles.some(role => {
      return rolePermissions.includes(role)
    })

    // 检查用户类型权限
    const hasUserType = rolePermissions.includes(userType)

    if (!hasRole && !hasUserType) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`need roles! Like v-hasRole="['admin','editor']"`)
  }
}

export default {
  inserted(el, binding) {
    checkRole(el, binding)
  },
  update(el, binding) {
    checkRole(el, binding)
  }
}